package FivechessClient;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

public class Game4 {
	BufferedImage table;
	BufferedImage black;
	BufferedImage white;

	BufferedImage selected;

	private static int BOARD_SIZE = 15;

	private final int TABLE_WIDTH = 535;
	private final int TABLE_HEIGHT = 536;

	private final int RATE = TABLE_WIDTH / BOARD_SIZE;

	private final int X_OFFSET = 5;
	private final int Y_OFFSET = 6;

	private int[][] board = new int[BOARD_SIZE][BOARD_SIZE];
	private int[][] computerScore = new int[BOARD_SIZE][BOARD_SIZE];

	JFrame f = new JFrame("五子棋--小熊");

	ChessBoard chessBoard = new ChessBoard();

	private static int selectedX = -1;
	private static int selectedY = -1;
	private static int computerX = -1;
	private static int computerY = -1;

	private static boolean flagGamer = false; // 记录玩家是否赢了
	private static boolean flagComputer = false; // 记录电脑是否赢了

	private static int computerscore = 0; // 电脑最大分数
	private static int comx, comy; // 玩家下子坐标

	private final int HUO = 1;
	private final int CHONG = 2;
	private static int chesscou = 0;

	private ArrayList<ChessXY4> chessListAI = new ArrayList<ChessXY4>();
	private ArrayList<ChessXY4> chessList = new ArrayList<ChessXY4>();
	private ArrayList<ChessXY4> chessLi = new ArrayList<ChessXY4>();

	Random rand = new Random();

	public void initto() {
		for (int i = 0; i < BOARD_SIZE; ++i) {
			for (int j = 0; j < BOARD_SIZE; ++j) {
				board[i][j] = 0;
				computerScore[i][j] = 0;
			}
		}
		chesscou = 0;
		computerX = -1;
		computerY = -1;
		flagGamer = false;
		flagComputer = false;
	}

	public boolean isRun(int x, int y) {
		if (board[x][y] == 0) {
			return true;
		}
		return false;
	}

	public boolean isWin(int f, int x, int y) {
		int i, count = 1;
		boolean up, down, right, left, rup, lup, rdown, ldown;
		up = down = right = left = rup = lup = rdown = ldown = true;
		/* 上下 */
		for (i = 1; i < 5; ++i) {
			if ((y + i) < BOARD_SIZE) {
				if (board[x][y + i] == f && down)
					count++;
				else
					down = false;
			}
			if ((y - i) >= 0) {
				if (board[x][y - i] == f && up)
					count++;
				else
					up = false;
			}
		}
		if (count >= 5) {
			return true;
		}
		count = 1;
		/* 左右 */
		for (i = 1; i < 5; ++i) {
			if ((x + i) < BOARD_SIZE) {
				if (board[x + i][y] == f && right)
					count++;
				else
					right = false;
			}
			if ((x - i) >= 0) {
				if (board[x - i][y] == f && left)
					count++;
				else
					left = false;
			}
		}
		if (count >= 5) {
			return true;
		}
		count = 1;
		/* 左上右下 */
		for (i = 1; i < 5; ++i) {
			if ((x + i) < BOARD_SIZE && (y + i) < BOARD_SIZE) {
				if (board[x + i][y + i] == f && rdown)
					count++;
				else
					rdown = false;
			}
			if ((x - i) >= 0 && (y - i) >= 0) {
				if (board[x - i][y - i] == f && lup)
					count++;
				else
					lup = false;
			}
		}
		if (count >= 5) {
			return true;
		}
		count = 1;
		/* 右上左下 */
		for (i = 1; i < 5; ++i) {
			if ((x + i) < BOARD_SIZE && (y - i) >= 0) {
				if (board[x + i][y - i] == f && rup)
					count++;
				else
					rup = false;
			}
			if ((x - i) >= 0 && (y + i) < BOARD_SIZE) {
				if (board[x - i][y + i] == f && ldown)
					count++;
				else
					ldown = false;
			}
		}
		if (count >= 5) {
			return true;
		}

		return false;
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public void Computer_AI() {
		computerscore = 0;
		for (int i = 0; i < BOARD_SIZE; ++i) {
			for (int j = 0; j < BOARD_SIZE; ++j) {
				computerScore[i][j] = 0;
			}
		}
		// AlphaBeta(2,-999999,999999,-1);
		// comx = chess.x;
		// comy = chess.y;
		// chess.x = 0;
		// chess.y = 0;
		// for(int i = 0; i < BOARD_SIZE; ++i)
		// {
		// for(int j = 0; j < BOARD_SIZE; ++j)
		// {
		// if(computerScore[i][j] == computerscore)
		// {
		// ChessXY4 chess = new ChessXY4(i, j);
		// chessList.add(chess);
		// }
		// }
		// }
		int a = getScore(-1);
		int b = getScore(1);
		if (a >= b) {
			for (int i = chessListAI.size(); i >= 0; --i) {
				board[chessListAI.get(0).x][chessListAI.get(0).y] = -1;
				ChessXY4 ch = new ChessXY4(chessListAI.get(0).x, chessListAI.get(0).y, getScore(1));
				chessLi.add(ch);
				board[chessListAI.get(0).x][chessListAI.get(0).y] = 0;
			}
			Collections.sort(chessLi, new Comparator() {
				public int compare(Object o1, Object o2) {
					return ((ChessXY4) o1).score - ((ChessXY4) o2).score;
				}
			});
			for (int i = 1; i < chessLi.size(); ++i) {
				if (chessLi.get(i).score != chessLi.get(0).score) {
					chessLi.remove(i);
				}
			}
			int n = rand.nextInt(chessLi.size());
			comx = chessLi.get(n).x;
			comy = chessLi.get(n).y;
			chessListAI.clear();
			chessList.clear();
			chessLi.clear();
		} else {
			boolean flag = true;
			check: for (int i = 0; i < chessListAI.size(); ++i) {
				for (int j = 0; j < chessList.size(); ++j) {
					if (chessListAI.get(i).x == chessList.get(j).x && chessListAI.get(i).y == chessList.get(j).y) {
						comx = chessListAI.get(i).x;
						comy = chessListAI.get(i).y;
						chessListAI.clear();
						chessList.clear();
						flag = false;
						break check;
					}
				}
			}
			if (flag) {
				int n = rand.nextInt(chessList.size()); // 电脑根据分值一样的点随机走，防止每次都走相同的步数
				comx = chessList.get(n).x;
				comy = chessList.get(n).y;
				chessListAI.clear();
				chessList.clear();
			}
		}
	}

	public int getScore(int color) {
		computerscore = 0;
		for (int i = 0; i < BOARD_SIZE; ++i) {
			for (int j = 0; j < BOARD_SIZE; ++j) {
				if (board[i][j] == 0) {
					if (isWin(color, i, j)) // 电脑能赢，故给分最高，因为可以结束，所以不再检测
					{
						computerscore = 100000;
						computerScore[i][j] = 100000;
					} else if (isWin(-color, i, j)) // 电脑不能赢，玩家能赢，要阻止，所以给12分
					{
						computerscore = 80000;
						computerScore[i][j] = 80000;
					} else if (isHuoOrChong(color, i, j, 4, HUO)) // 电脑玩家都不能赢，电脑能形成活四，给11分
					{
						computerscore = (computerscore > 40000 ? computerscore : 40000);
						computerScore[i][j] = 40000;
					} else if (isHuoOrChong(color, i, j, 4, CHONG)) // 电脑玩家都不能赢，电脑能形成冲四，给10分
					{
						computerscore = (computerscore > 10000 ? computerscore : 10000);
						computerScore[i][j] = 10000;
					} else if (isHuoOrChong(-color, i, j, 4, HUO)) // 电脑玩家都不能赢，玩家能形成活四，给9分
					{
						computerscore = (computerscore > 7000 ? computerscore : 7000);
						computerScore[i][j] = 7000;
					} else if (isHuoOrChong(color, i, j, 3, HUO)) // 电脑玩家都不能赢，电脑能形成活三，给8分
					{
						computerscore = (computerscore > 4000 ? computerscore : 4000);
						computerScore[i][j] = 4000;
					} else if (isHuoOrChong(-color, i, j, 4, CHONG)) // 电脑玩家都不能赢，玩家能形成冲四，给7分
					{
						computerscore = (computerscore > 1000 ? computerscore : 1000);
						computerScore[i][j] = 1000;
					} else if (isHuoOrChong(color, i, j, 3, CHONG)) // 电脑玩家都不能赢，电脑能形成冲三，给6分
					{
						computerscore = (computerscore > 700 ? computerscore : 700);
						computerScore[i][j] = 700;
					} else if (isHuoOrChong(-color, i, j, 3, HUO)) // 电脑玩家都不能赢，玩家能形成冲三，给4分
					{
						computerscore = (computerscore > 500 ? computerscore : 500);
						computerScore[i][j] = 500;
					} else if (isHuoOrChong(color, i, j, 2, HUO)) // 电脑玩家都不能赢，电脑能形成活二，给5分
					{
						computerscore = (computerscore > 400 ? computerscore : 400);
						computerScore[i][j] = 400;
					} else if (isHuoOrChong(-color, i, j, 3, CHONG)) // 电脑玩家都不能赢，玩家能形成冲三，给4分
					{
						computerscore = (computerscore > 200 ? computerscore : 200);
						computerScore[i][j] = 200;
					} else if (isHuoOrChong(-color, i, j, 2, HUO)) // 电脑玩家都不能赢，玩家能形成活二，给3分
					{
						computerscore = (computerscore > 80 ? computerscore : 80);
						computerScore[i][j] = 80;
					} else if (isHuoOrChong(color, i, j, 2, CHONG)) // 电脑玩家都不能赢，电脑能形成冲二，给2分
					{
						computerscore = (computerscore > 50 ? computerscore : 50);
						computerScore[i][j] = 50;
					} else if (isHuoOrChong(-color, i, j, 2, CHONG)) // 电脑玩家都不能赢，玩家能形成冲二，给1分
					{
						computerscore = (computerscore > 10 ? computerscore : 10);
						computerScore[i][j] = 10;
					} else {
						computerScore[i][j] = 0;
					}
				}
			}
		}
		for (int i = 0; i < BOARD_SIZE; ++i) {
			for (int j = 0; j < BOARD_SIZE; ++j) {
				if (computerScore[i][j] == computerscore) {
					ChessXY4 AI = new ChessXY4(i, j, computerscore);
					if (color == -1) {
						chessListAI.add(AI);
					} else {
						chessList.add(AI);
					}
				}
			}
		}
		return computerscore;
	}

	// public int AlphaBeta(int depth,int alpha,int beta,int color)
	// {
	// int curValue = 0;
	// if(depth == 0)
	// {
	// return getScore();
	// }
	// else
	// {
	// for(int i = 0; i < BOARD_SIZE; ++i)
	// {
	// for(int j = 0; j < BOARD_SIZE; ++j)
	// {
	// if(isRun(i, j))
	// {
	// board[i][j] = color;
	// curValue = -AlphaBeta(depth-1, -beta, -alpha, -color);
	//// System.out.println(i + " " + j + " " + curValue);
	// board[i][j] = 0;
	// if(curValue >= beta)
	// {
	// return beta;
	// }
	// if(curValue > alpha)
	// {
	// alpha = curValue;
	// chess.x = i;
	// chess.y = j;
	// }
	// }
	// }
	// }
	// return alpha;
	// }
	// }

	private boolean isHuoOrChong(int f, int x, int y, int num, int hORc) // 活
	{

		num += 1;
		int i, count = 1;
		boolean terminal1 = false;
		boolean terminal2 = false;
		boolean up, down, right, left, rup, lup, rdown, ldown;
		up = down = right = left = rup = lup = rdown = ldown = true;
		/* 上下 */
		for (i = 1; i < num; ++i) {
			if ((y + i) < BOARD_SIZE) {
				if (board[x][y + i] == f && down)
					count++;
				else {
					if (board[x][y + i] == 0 && down) {
						terminal1 = true;
					}
					down = false;
				}
			}
			if ((y - i) >= 0) {
				if (board[x][y - i] == f && up)
					count++;
				else {
					if (board[x][y - i] == 0 && up) {
						terminal2 = true;
					}
					up = false;
				}
			}
		}
		if (count == num - 1 && hORc == HUO && terminal1 && terminal2) {
			return true;
		}
		if (count == num - 1 && hORc == CHONG && ((terminal1 && !terminal2) || (!terminal1 && terminal2))) {
			return true;
		}
		count = 1;
		terminal1 = false;
		terminal2 = false;
		/* 左右 */
		for (i = 1; i < num; ++i) {
			if ((x + i) < BOARD_SIZE) {
				if (board[x + i][y] == f && right)
					count++;
				else {
					if (board[x + i][y] == 0 && right) {
						terminal1 = true;
					}
					right = false;
				}
			}
			if ((x - i) >= 0) {
				if (board[x - i][y] == f && left)
					count++;
				else {
					if (board[x - i][y] == 0 && left) {
						terminal2 = true;
					}
					left = false;
				}
			}
		}
		if (count == num - 1 && hORc == HUO && terminal1 && terminal2) {
			return true;
		}
		if (count == num - 1 && hORc == CHONG && ((terminal1 && !terminal2) || (!terminal1 && terminal2))) {
			return true;
		}
		count = 1;
		terminal1 = false;
		terminal2 = false;
		/* 左上右下 */
		for (i = 1; i < num; ++i) {
			if ((x + i) < BOARD_SIZE && (y + i) < BOARD_SIZE) {
				if (board[x + i][y + i] == f && rdown)
					count++;
				else {
					if (board[x + i][y + i] == 0 && rdown) {
						terminal1 = true;
					}
					rdown = false;
				}
			}
			if ((x - i) >= 0 && (y - i) >= 0) {
				if (board[x - i][y - i] == f && lup)
					count++;
				else {
					if (board[x - i][y - i] == 0 && lup) {
						terminal2 = true;
					}
					lup = false;
				}
			}
		}
		if (count == num - 1 && hORc == HUO && terminal1 && terminal2) {
			return true;
		}
		if (count == num - 1 && hORc == CHONG && ((terminal1 && !terminal2) || (!terminal1 && terminal2))) {
			return true;
		}
		count = 1;
		terminal1 = false;
		terminal2 = false;
		/* 右上左下 */
		for (i = 1; i < num; ++i) {
			if ((x + i) < BOARD_SIZE && (y - i) >= 0) {
				if (board[x + i][y - i] == f && rup)
					count++;
				else {
					if (board[x + i][y - i] == 0 && rup) {
						terminal1 = true;
					}
					rup = false;
				}
			}
			if ((x - i) >= 0 && (y + i) < BOARD_SIZE) {
				if (board[x - i][y + i] == f && ldown)
					count++;
				else {
					if (board[x - i][y + i] == 0 && ldown) {
						terminal2 = true;
					}
					ldown = false;
				}
			}
		}
		if (count == num - 1 && hORc == HUO && terminal1 && terminal2) {
			return true;
		}
		if (count == num - 1 && hORc == CHONG && ((terminal1 && !terminal2) || (!terminal1 && terminal2))) {
			return true;
		}

		return false;
	}

	@SuppressWarnings("deprecation")
	public void init() throws Exception {
		table = ImageIO.read(new File("image/board.jpg"));
		black = ImageIO.read(new File("image/black.gif"));
		white = ImageIO.read(new File("image/white.gif"));
		selected = ImageIO.read(new File("image/selected.gif"));

		for (int i = 0; i < BOARD_SIZE; ++i) {
			for (int j = 0; j < BOARD_SIZE; ++j) {
				board[i][j] = 0;
				computerScore[i][j] = 0;
			}
		}
		chessBoard.setPreferredSize(new Dimension(TABLE_WIDTH, TABLE_HEIGHT));

		chessBoard.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
				int xPos = (int) ((e.getX() - X_OFFSET) / RATE);
				int yPos = (int) ((e.getY() - Y_OFFSET) / RATE);
				if (isRun(xPos, yPos)) {
					flagGamer = isWin(1, xPos, yPos);
					board[xPos][yPos] = 1;
					chesscou++;
					chessBoard.repaint();
					if (chesscou == (BOARD_SIZE * BOARD_SIZE)) {
						JOptionPane.showMessageDialog(null, "不相上下！！！\n再来一盘吧！！！", "结束", JOptionPane.ERROR_MESSAGE);
						initto();
					} else {
						Computer_AI(); // 电脑下棋，AI算法
						chesscou++;
						chessBoard.repaint();
						flagComputer = isWin(-1, comx, comy);
						board[comx][comy] = -1;
						computerX = comx;
						computerY = comy;
					}
				}
				if (flagGamer) {
					JOptionPane.showMessageDialog(null, "厉害厉害！！！\n你赢了！！！", "结束", JOptionPane.ERROR_MESSAGE);
					initto();
				} else if (flagComputer) {
					JOptionPane.showMessageDialog(null, "哈哈哈哈！！！\n你输了！！！", "结束", JOptionPane.ERROR_MESSAGE);
					initto();
				}
			}

			public void mouseExited(MouseEvent e) {
				selectedX = -1;
				selectedY = -1;
				chessBoard.repaint();
			}
		});
		chessBoard.addMouseMotionListener(new MouseMotionAdapter() {
			public void mouseMoved(MouseEvent e) {
				selectedX = (e.getX() - X_OFFSET) / RATE;
				selectedY = (e.getY() - Y_OFFSET) / RATE;

				chessBoard.repaint();
			}
		});
		f.add(chessBoard);
		f.setCursor(1);
		f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		f.setResizable(false);
		f.pack();
		f.setVisible(true);
	}

	public static void main(String[] args) throws Exception {
		Game4 game = new Game4();
		game.init();
	}

	@SuppressWarnings("serial")
	class ChessBoard extends JPanel {
		public void paint(Graphics g) {
			g.drawImage(table, 0, 0, null);
			if (selectedX >= 0 && selectedY >= 0) {
				g.drawImage(selected, selectedX * RATE + X_OFFSET, selectedY * RATE + Y_OFFSET, null);
			}
			if (computerX >= 0 && computerY >= 0) {
				g.drawImage(selected, computerX * RATE + X_OFFSET, computerY * RATE + Y_OFFSET, null);
			}
			for (int i = 0; i < BOARD_SIZE; ++i) {
				for (int j = 0; j < BOARD_SIZE; ++j) {
					if (board[i][j] == 1) {
						g.drawImage(black, i * RATE + X_OFFSET, j * RATE + Y_OFFSET, null);
					}
					if (board[i][j] == -1) {
						g.drawImage(white, i * RATE + X_OFFSET, j * RATE + Y_OFFSET, null);
					}
				}
			}
		}
	}
}

class ChessXY4 {
	int x;
	int y;
	int score;

	public ChessXY4(int x, int y, int score) {
		this.x = x;
		this.y = y;
		this.score = score;
	}
}
